from pymongo import MongoClient
from bson.objectid import ObjectId
from datetime import datetime
import os

DB_USER = os.environ.get('DB_USER')
DB_PASSWORD = os.environ.get('DB_PASSWORD')
DB_IP = os.environ.get('DB_IP') or "10.176.52.112"
DB_PORT = os.environ.get('DB_PORT') or "27777"


class DB:

    def __init__(self, user=DB_USER, password=DB_PASSWORD, ip=DB_IP, port=DB_PORT):
        self.client = MongoClient("mongodb://{}:{}@{}:{}/".format(user, password, ip, port))
        self.arXiv = self.client["arXiv"]
        self.article = self.arXiv["article"]
        self.user = self.arXiv["user"]
        self.recommendation = self.arXiv["recommendation"]
        self.classification = self.arXiv["classification"]
        self.document = self.arXiv["document"]

    def create_data(self, lemmatized, appear=0, recommend=0, amount=0, turns=0, recommender={}):
        """
        :param lemmatized: lemmatizer.lemmatize(rec.lower())后形式
        :param appear: 出现的论文篇数
        :param recommend: 推荐论文中出现的篇数
        :param amount: 被推荐日起所有论文的篇数
        :param turns: 每一千篇加1
        :param recommender: 关联推荐人
               recommender.uId 推荐人user._id
               recommender.format 推荐词的原型
        :return:
        """
        data = self.recommendation.insert_one({
            "lemmatized": lemmatized,
            "appear": appear,
            "recommend": recommend,
            "amount": amount,
            "turns": turns,
            "recommender": recommender
        })
        return str(data.inserted_id)

    def create_document(self, docNo, docTitle, createDate=datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")):
        """
        :param docNo: 飞书文档的编号
        :param docTitle: 飞书文档的标题
        :param createDate: 创建时间
        :return:
        """
        data = self.document.insert_one({
            "docNo": docNo,
            "docTitle": docTitle,
            "createDate": createDate
        })
        return str(data.inserted_id)

    def update_data(self, _id, uId, format, add=True):
        uId = str(uId)
        if add:
            res = self.recommendation.update_one({
                "_id": ObjectId(_id)
            }, {
                "$set": {f"recommender.{uId}": format}
            })
        else:
            res = self.recommendation.update_one({
                "_id": ObjectId(_id)
            }, {
                "$unset": {f"recommender.{uId}": ""}
            })    
        return res.matched_count, res.modified_count

    def update_user(self, uId, recId, add=True):
        if add:
            res = self.user.update_one({
                "_id": uId,
            }, {
                "$addToSet": {"rlist": ObjectId(recId)}
            })
        else:
            res = self.user.update_one({
                "_id": uId,
            }, {
                "$pull": {"rlist": ObjectId(recId)}
            })
        return res.matched_count, res.modified_count

    def recommend_update(self, _id, appear, recommend, amount):
        print(_id, appear, recommend, amount)
        res = self.recommendation.update_one({
            "_id": _id,
        }, {
            "$set": {"appear": appear, "recommend": recommend, "amount": amount}
        })
        return res.matched_count, res.modified_count

    def article_recommend(self, _id):
        res = self.article.update_one({
            "_id": _id,
        }, {
            "$set": {"republish": True},
            "$inc": {"recommend": 1}
        })
        return res.matched_count, res.modified_count

    def article_expire(self):
        res = self.article.update_many({}, {
            "$unset": {"recommend": "", "republish": False}
        })
        return res.matched_count, res.modified_count

    def article_republish_rank(self):
        res = self.article.aggregate([
            {
                "$match": {
                    "republish": True
                }
            },
            {
                "$sort": {"recommend": -1}
            }
        ])
        return list(res)

    def document_link(self):
        res = self.document.find({})
        return {i['createDate'].strftime("%Y-%m-%d"): i['docNo'] for i in res if 'createDate' in i}

db = DB()


# dump
# D:\software\MongoDB\mongodb-database-tools-windows-x86_64-100.5.0\bin\mongodump --host 10.176.52.112 --port 27017 -d arXiv --out D:\software\MongoDB\dump\mongo112
# restore
# mongorestore --host 81.68.174.180 --port 27777 --authenticationDatabase admin --username admin --password adminNLP -d arXiv "D:\software\MongoDB\dump\mongodata\arXiv"
if __name__ == '__main__':
    # Terminal > Integrated > Env:Windows
    # class_list = {c['domain']: [] for c in list(db.classification.find({}))}
    # print(class_list)
    print(sorted(list(db.classification.find({})), key=lambda dom: dom['order']))
    # test = {'bert': [2, 67, 12], 'class': [21, 3, 8], 'trans': [74, 8, 16]}
    # for a in test.values():
    #     list.sort(a)
    # print(test)
